<template>
  <div class="jiangchengtb">
    <div style="width: 1200px;display: flex;justify-content: space-between;margin: 0px auto;">
      <router-link to="/main/renshi/yuangongdangan/yuangongguanli/yuangongguanli"
        style="padding-top: 10px;">返回</router-link>
      <router-link to="/main/renshi/kaoqing/jiangchen/jiangchengtb-list" style="padding-top: 10px;">列表</router-link>
    </div>
    <div class="form-container">
      <h2>奖惩提报单</h2>
      <div class="form-actions">
        <button @click="addRecord">新增</button>&emsp;
        <button @click="deleteSelectedRecords">批量删除</button>&emsp;
        <button @click="saveData">保存</button>
      </div>
      <table border="1">
        <thead>
          <tr>
            <th><input type="checkbox" @change="toggleSelectAll" v-model="selectAll"></th>
            <th>序号</th>
            <th>工号</th>
            <th>姓名</th>
            <th>部门名称</th>
            <th>奖惩类别</th>
            <th>事由</th>
            <th>金额</th>
            <th>职务</th>
            <th>奖惩日期</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(record, index) in rewardPunishmentRecords" :key="index">
            <td><input type="checkbox" v-model="selectedRecords" :value="index" @change="updateSelectAll" /></td>
            <td>{{ index + 1 }}</td>
            <td><input v-model="record.employeeId" /></td>
            <td><input v-model="record.name" /></td>
            <td><input v-model="record.departmentName" /></td>
            <td><input v-model="record.rewardPunishmentType" /></td>
            <td><input v-model="record.reason" /></td>
            <td><input v-model="record.amount" type="number" /></td>
            <td><input v-model="record.position" /></td>
            <td><input v-model="record.date" type="date" /></td>
            <td><input v-model="record.remark" /></td>
          </tr>
          <tr>
            <td colspan="4">
              <span>批准：<input style="width: 150px;" v-model="approvalPerson" maxlength="4" title="只能四个字以内" /></span>
            </td>
            <td colspan="4">
              <span>审核：<input style="width: 150px;" v-model="reviewPerson" maxlength="4" title="只能四个字以内" /></span>
            </td>
            <td colspan="4">
              <span>制作：<input style="width: 150px;" v-model="maker" maxlength="4" title="只能四个字以内" /></span>
            </td>
          </tr>
        </tbody>
      </table>
      <p>表单编号及版本：AM-JY-022 A/0 保存期限：长期</p>
    </div>
  </div>
</template>

<script>
import { saveRewardPunishmentReport, getRewardPunishmentReportDetail, batchSaveRewardPunishmentReport } from '@/api/rewardPunishmentReport';

export default {
  data() {
    return {
      rewardPunishmentRecords: [
        this.getEmptyRecord()
      ],
      approvalPerson: '',
      reviewPerson: '',
      maker: '',
      selectedRecords: [],
      selectAll: false,
      isEdit: false,
      editId: null
    };
  },
  created() {
    // 检查是否是编辑模式
    const id = this.$route.query.id;
    if (id) {
      this.isEdit = true;
      this.editId = id;
      this.fetchDetail(id);
    }
  },
  methods: {
    getEmptyRecord() {
      return {
        employeeId: '',
        name: '',
        departmentName: '',
        rewardPunishmentType: '',
        reason: '',
        amount: 0,
        position: '',
        date: '',
        remark: ''
      };
    },
    async fetchDetail(id) {
      try {
        const response = await getRewardPunishmentReportDetail(id);
        const data = response.data;
        // 设置表单数据
        this.rewardPunishmentRecords = [{
          id: data.id,
          employeeId: data.employeeId,
          name: data.name,
          departmentName: data.departmentName,
          rewardPunishmentType: data.rewardPunishmentType,
          reason: data.reason,
          amount: data.amount,
          position: data.position,
          date: data.date ? data.date.split('T')[0] : '',
          remark: data.remark
        }];
        this.approvalPerson = data.approvalPerson;
        this.reviewPerson = data.reviewPerson;
        this.maker = data.maker;
      } catch (error) {
        this.$message.error('获取详情失败：' + error.message);
      }
    },
    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedRecords = this.rewardPunishmentRecords.map((_, index) => index);
      } else {
        this.selectedRecords = [];
      }
    },
    updateSelectAll() {
      this.selectAll = this.selectedRecords.length === this.rewardPunishmentRecords.length;
    },
    deleteSelectedRecords() {
      if (confirm('确定要删除选中的记录吗？')) {
        this.selectedRecords.sort((a, b) => b - a).forEach(index => {
          this.rewardPunishmentRecords.splice(index, 1);
        });
        this.selectedRecords = [];
        this.selectAll = false;
      }
    },
    addRecord() {
      this.rewardPunishmentRecords.push(this.getEmptyRecord());
      this.updateSelectAll();
    },
    async saveData() {
      try {
        if (this.rewardPunishmentRecords.length === 0) {
          this.$message.error('请至少添加一条记录');
          return;
        }

        // 验证必填字段
        for (const record of this.rewardPunishmentRecords) {
          if (!record.employeeId) throw new Error('请填写工号');
          if (!record.name) throw new Error('请填写姓名');
          if (!record.departmentName) throw new Error('请填写部门名称');
          if (!record.rewardPunishmentType) throw new Error('请填写奖惩类别');
          if (!record.reason) throw new Error('请填写事由');
          if (!record.amount) throw new Error('请填写金额');
          if (!record.date) throw new Error('请选择奖惩日期');
        }

        // 准备批量保存的数据
        const dataToSave = this.rewardPunishmentRecords.map(record => ({
          ...record,
          approvalPerson: this.approvalPerson,
          reviewPerson: this.reviewPerson,
          maker: this.maker
        }));

        await batchSaveRewardPunishmentReport(dataToSave);
        this.$message.success('保存成功');
        this.$router.push('/main/renshi/kaoqing/jiangchen/jiangchengtb-list');
      } catch (error) {
        this.$message.error('保存失败：' + error.message);
      }
    }
  }
};
</script>

<style scoped lang="scss">
.jiangchengtb {
  position: relative;
  /* 设置相对定位 */
  height: 100vh;

}

.form-container {
  width: 1200px;
  max-width: 1200px;
  margin: 0 auto;

}

.form-actions {
  display: flex;
  margin-bottom: 10px;
}

table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
  white-space: nowrap;
}

input {
  text-align: center;
  width: 80%;
  border: none;
}
</style>